import { createStore, createLogger } from 'vuex'


// 插件
const myPlugin = (store: any) => {
  // 当 store 初始化后调用
  store.subscribe((mutation: any, state: State) => {
    // 每次 mutation 之后调用
    // mutation 的格式为 { type, payload }
    localStorage.setItem('user', JSON.stringify(state.user))
  })
}


const user = JSON.parse(localStorage.getItem('user') as string) || {}

export interface UserState {
  isLogin: boolean
  avator: string,
  username: string,
  token: string
}
export interface State {
  user: UserState,
  userHistory: any[]
}

export default createStore<State>({
  state: {
    user: {
      isLogin: user.isLogin || false,
      avator: user.avator || '',
      username: user.username || '',
      token: user.token || ''
    },
    userHistory: []
  },
  mutations: {
    setUser(state, payload) {
      state.user = { ...state.user, ...payload }
    },
    quit(state) {
      state.user = { isLogin: false, username: '', token: '', avator: '' }
      localStorage.removeItem('user')
    },
    addUserHistory(state, payload) {
      const index = state.userHistory.findIndex(v => v.id === payload.id)

      if (index !== -1) {
        state.userHistory = state.userHistory.filter(v => v.id !== payload.id)
      }
      
      state.userHistory.unshift(payload)
    }
  },
  actions: {
  },
  modules: {
  },
  plugins: [myPlugin, createLogger()]
})
